<template>
	<view class="container">
		<bt-cropper ref="croper" :ratio="ratio" fileType="png" showGrid :imageSrc="imageSrc">
			<view class="footer">
				<view class="btnGroup">
					<view class="btn choose" @click="chooseImage">
						选择图片
					</view>
					<view class="btn" @click="onCrop">
						确定
					</view>
				</view>
			</view>
		</bt-cropper>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imageSrc: "",
				dWidth: 500,
				// 输出的宽高比例
				ratio: 1,
				activeIndex: 1,
				// 默认位置示例,可以传递给裁剪组件
				initPosition: {
					height: 2601.9554188501556,
					left: 874.5412774360142,
					top: 1640.5454545454545,
					width: 1590.4913040176198
				},
        state: 0,
        where: ''
			}
		},
		onLoad(options) {
      this.imageSrc = options.filePath
      this.where = options.where
    },
		methods: {
			chooseImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original'],
					success: (res) => {
						let tempFilePaths = res.tempFilePaths[0]
						this.imageSrc = tempFilePaths
					}
				})
			},
			onCrop(cb) {
        if(this.state == 0) {
          this.state = 1
          this.$refs.croper.crop().then(([err, res]) => {
          	if (!err) {
          		// #ifdef H5
          		this.h5SaveCanvasImage(res.tempFilePath)
          		// #endif
          		// #ifndef H5
              let filePath = res.tempFilePath
              if(this.where == "set") {
                uniCloud.uploadFile({
                			filePath: filePath,
                      cloudPath: 'avatar.jpg',
                       success: async (res) => {
                        uni.setStorageSync('jiayi_avatarUrl', res.fileID)
                        uni.navigateBack()
                        const avatar_url = uni.getStorageSync('jiayi_avatarUrl')
                        const avatarUrlArray = uni.getStorageSync('jiayi_avatarUrlArray')
                        avatarUrlArray.push(avatar_url)
                        const openid = uni.getStorageSync('jiayi_openid')
                        const db = uniCloud.database()
                        const collection = db.collection('jiayi-user')
                        const data = await collection.where({openID: openid}).update({avatarUrl: avatar_url, avatarUrlArray: avatarUrlArray})
                        this.state = 0
                      }
                		});
                  } else if(this.where = "sell") {
                    uniCloud.uploadFile({
                    			filePath: filePath,
                          cloudPath: 'shangpin.jpg',
                           success: async (res) => {
                            uni.setStorageSync('jiayi_exchange', res.fileID)
                            uni.navigateBack()
                            this.state = 0
                          }
                    		});
                  }
          		// #endif
          	}
          })
        }
			},
			h5SaveCanvasImage(base64) {
				var arr = base64.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				let blob = new Blob([u8arr], {
					type: mime
				});
				var a = document.createElement("a")
				a.setAttribute("href", URL.createObjectURL(blob))
				a.setAttribute("download", +new Date() + '.' + mime.split('/')[1])
				a.setAttribute("target", "_blank")
				a.click()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		box-sizing: border-box;
		// #ifndef H5
		height: 100vh;
		// #endif
		// #ifdef H5
		height: 100%;
		// #endif
	}

	uni-page-body {
		height: 100%;
	}

	.footer {
		.btnGroup {
			display: flex;
			align-items: center;
			justify-content: space-around;
			background-color: #000000;
			height: calc(100rpx + env(safe-area-inset-bottom));
			padding-bottom: 20rpx;
			padding-top: 20rpx;
			width: 100%;

			.btn {
				width: 300rpx;
				background-color: #007AFF;
				color: #FFFFFF;
				border-radius: 99px;
				text-align: center;
				color: #FFFFFF;
				line-height: 70rpx;

				&.choose {
					margin-right: 20rpx;
					background-color: #F0AD4E;
				}
			}
		}
	}
</style>
